package com.yuhao.init.utils;

import java.util.concurrent.CompletableFuture;

/**
 * @Author: yuhao
 * @Date: 2024/5/4 16:51
 */
public class WaitNotifyExample {
    public static void main(String[] args) {
        Message message = new Message();

        // 创建生产者线程
        Thread producerThread = new Thread(new Producer(message));
        // 创建消费者线程
        Thread consumerThread = new Thread(new Consumer(message));

        // 启动线程
        producerThread.start();
//        consumerThread.start();
    }
}

class Message {
    private String content;
    private boolean empty = true;

    // 生产者调用的方法，用于向消息对象设置内容
    public synchronized void setContent(String content) {
        while (!empty) {
            try {
                // 对象不为空，等待消费者消费
                wait();
                System.out.println("wait...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.content = content;
        empty = false;
        notifyAll(); // 唤醒等待队列中的消费者线程
    }

    // 消费者调用的方法，用于获取消息对象的内容
    public synchronized String getContent() {
        while (empty) {
            try {
                // 对象为空，等待生产者生产
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String message = this.content;
        empty = true;
        notifyAll(); // 唤醒等待队列中的生产者线程
        return message;
    }
}

class Producer implements Runnable {
    private Message message;

    public Producer(Message message) {
        this.message = message;
    }

    @Override
    public void run() {
        String[] messages = {"Hello", "World", "Java"};
        for (String msg : messages) {
            message.setContent(msg);
            System.out.println("生产者生产消息：" + msg);
            try {
                Thread.sleep(1000); // 模拟生产过程
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {
    private Message message;

    public Consumer(Message message) {
        this.message = message;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            String msg = message.getContent();
            System.out.println("消费者消费消息：" + msg);
            try {
                Thread.sleep(1000); // 模拟消费过程
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}